import { _decorator, Collider2D, Component, Contact2DType, EventTouch, input, Input, Node, RigidBody2D, v2, v3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BirdCtrl')
export class BirdCtrl extends Component {
    
    private rigidBody: RigidBody2D
    private collider: Collider2D
    
    private angleBack: number = 30

    onLoad() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
    }

    start() {
        this.rigidBody = this.node.getComponent(RigidBody2D)
        // this.collider = this.node.getComponent(Collider)

        // 注册单个碰撞体的回调函数
        this.collider = this.getComponent(Collider2D)
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
            // collider.on(Contact2DType.END_CONTACT, this.onEndContact, this)
        }
    }

    update(deltaTime: number) {
        if (this.node.angle > -60) this.node.angle -= this.angleBack * deltaTime
    }

    onTouchStart(event: EventTouch) {
        // 施加升力
        const lift = v2(0, 10)
        // this.rigidBody.applyForceToCenter(lift, true)
        this.rigidBody.linearVelocity  = lift

        // 调整飞行角度
        // this.node.setRotationFromEuler(v3(0, 0, 30))
        this.node.angle = 30
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
        console.log(otherCollider.tag)
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
    }
}


